package cn.edu.hbwe.book.servlet.order;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import com.sun.org.apache.bcel.internal.generic.IREM;

import cn.edu.hbwe.book.entity.Book;
import cn.edu.hbwe.book.entity.OrderItem;
import cn.edu.hbwe.book.entity.Orders;
import cn.edu.hbwe.book.entity.User;
import cn.edu.hbwe.book.service.OrderService;
import cn.edu.hbwe.book.utils.IdUtils;
/**
 * Servlet implementation class CreateOrderServlet
 */
public class CreateOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		//得到当前用户
				HttpSession session = request.getSession();
				User user = (User) session.getAttribute("user");
				//从购物车中获取商品信息
				Map<Book, Integer> cart = (Map<Book, Integer>)session.getAttribute("cart");
				//将数据封装到订单对象中
				Orders order = new Orders();
				try {
					BeanUtils.populate(order, request.getParameterMap());
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				order.setId(IdUtils.getUUId());// 封装订单id
				order.setUser(user);// 封装用户信息到订单.
				for (Book b : cart.keySet()) {
					OrderItem item = new OrderItem();
					item.setOrder(order);
					item.setBuyNum(cart.get(b));
					item.setBook(b);
					order.getOrderItems().add(item);
				}
				System.out.println(order);
				// 调用service中添加订单操作.
				OrderService service = new OrderService();
				service.addOrder(order);
				response.sendRedirect(request.getContextPath() + "/bookweb/createOrderSuccess.jsp");
			}

}
